package com.qf.cx.simplenms.core.api.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.qf.cx.simplenms.core.api.Bootsrap;
import com.qf.cx.simplenms.core.spi.Updater;
import com.qf.cx.simplenms.persist.entity.SwitchEntity;
import com.qf.cx.simplenms.persist.service.api.SwitchService;
import com.qf.cx.simplenms.subscriber.api.Subscriber;
import com.qf.cx.simplenms.subscriber.api.SubscriberManager;

public class BootsrapImpl implements Bootsrap {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private List<Updater> updaters;
	@Autowired
	private SubscriberManager subscriberManager;
	@Autowired
	private SwitchService switchService;

	private boolean isAlive = false;
	private Thread thread = null;

	private final long cycle;

	public BootsrapImpl(final long cycle) {
		this.cycle = cycle;
	}

	@Override
	@PostConstruct
	public synchronized void start() {
		thread = new Thread("CONFIG_UPDATING_THREAD") {
			@Override
			public void run() {
				run0();
			}
		};

		thread.start();
	}

	void run0() {
		isAlive = true;
		switchService.deleteAll();

		start0();
		for (;;) {
			try {
				TimeUnit.SECONDS.sleep(cycle);

				for (SwitchEntity oneSwitch = switchService.getOneSwitch(); oneSwitch != null; oneSwitch = switchService
						.getOneSwitch()) {
					logger.info("configuration updating");
					start0();
					logger.info("configuration updated");
					switchService.deleteSwitch(oneSwitch);
				}
			} catch (InterruptedException ignore) {
				logger.error("main thread interrupted");
				isAlive = false;
				break;
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}

	private void start0() {
		for (Updater updater : updaters) {
			try {
				updater.update();
			} catch (Exception e) {
				logger.error("", e);
			}
		}

		for (Subscriber subscriber : subscriberManager.getSubscribers()) {
			subscriber.startIfNecessary();
		}
	}

	@Override
	public synchronized void stop() {
		if (thread != null) {
			thread.interrupt();
		}
	}

	@Override
	public boolean isAlive() {
		return isAlive;
	}

}
